package com.qf.controller;

import com.qf.Constant.AuthConstant;
import com.qf.Constant.CarConstant;
import com.qf.entity.User;
import com.qf.feign.CarService;
import com.qf.feign.UserService;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/16/17:37
 * @Description:
 */
@RestController
@RequestMapping("/oauth")
public class oauthController {
    @Autowired
    private  UserService userService;
    @Autowired
    private CarService carService;
    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public void  login(@CookieValue(name = CarConstant.ANNIO_CAR_COOKIE_NAME,defaultValue = "") String anoId, AuthCallback callback, HttpSession httpSession, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        //根据code获取AccessToken
        AuthResponse login = authRequest.login(callback);
        //判断是否授权成功
        if (login.ok()) {
            //认证授权成功
            AuthUser data = (AuthUser) login.getData();
            //判断用户是否第一次登陆.
            String uuid = data.getUuid();
            User user = userService.getUserByUuid(uuid);
            if (user==null) {
                user = new User();
                user.setUsername(data.getUsername());
                user.setOauthId(data.getUuid());
                userService.addUser(user);
            }
            httpSession.setAttribute(AuthConstant.AUTH_SESSION,user);
            //合并购物车
            carService.mergeCar(user.getId(),anoId);
            response.sendRedirect("http://localhost/home");
        }else {
            response.sendRedirect("http://localhost/toLogin?msg=认证失败");
        }

    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("7qg0q1YR5dXA8CdD201lK0al")
                .clientSecret("mlrqwzE2170xS4O49r0A0b8aCrSOtKmO")
                .redirectUri("http://localhost/auth/oauth/callback")
                .build());
    }
}
